ReactJS Ultra For Beginners

🎯 The useRef Hook


What is useRef?

  • A React Hook that returns a mutable ref object
  • Persists between re-renders without causing re-renders
  • Used to access DOM elements directly
  • Can store any mutable value

📝 Basic Syntax

import { useRef } from "react"; function TextInputWithFocusButton() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus the input</button> </> ); }

🔑 Core Concepts

1. Creating a Ref:

const myRef = useRef(initialValue);

2. Accessing the Ref:

// Access the current value console.log(myRef.current); // Update the current value myRef.current = newValue;

3. Attaching to DOM Elements:

<input ref={inputRef} /> <div ref={divRef} /> <video ref={videoRef} />

🎯 Common Use Cases

1. Focus Management:

function LoginForm() { const emailRef = useRef(null); const passwordRef = useRef(null); const handleEmailSubmit = (e) => { e.preventDefault(); passwordRef.current.focus(); }; const handlePasswordSubmit = (e) => { e.preventDefault(); // Handle login }; return ( <form> <input ref={emailRef} type="email" placeholder="Email" onKeyDown={(e) => e.key === "Enter" && handleEmailSubmit(e)} /> <input ref={passwordRef} type="password" placeholder="Password" onKeyDown={(e) => e.key === "Enter" && handlePasswordSubmit(e)} /> </form> ); }

2. Measuring DOM Elements:

function MeasureElement() { const elementRef = useRef(null); const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); useEffect(() => { if (elementRef.current) { const rect = elementRef.current.getBoundingClientRect(); setDimensions({ width: rect.width, height: rect.height, }); } }, []); return ( <div ref={elementRef}> <p>Width: {dimensions.width}px</p> <p>Height: {dimensions.height}px</p> </div> ); }

3. Storing Previous Values:

function Counter() { const [count, setCount] = useState(0); const prevCountRef = useRef(); useEffect(() => { prevCountRef.current = count; }); const prevCount = prevCountRef.current; return ( <div> <p>Current: {count}</p> <p>Previous: {prevCount}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }

4. Video/Audio Controls:

function VideoPlayer() { const videoRef = useRef(null); const play = () => { videoRef.current.play(); }; const pause = () => { videoRef.current.pause(); }; const skipTo = (seconds) => { videoRef.current.currentTime = seconds; }; return ( <div> <video ref={videoRef} src="video.mp4" /> <button onClick={play}>Play</button> <button onClick={pause}>Pause</button> <button onClick={() => skipTo(30)}>Skip to 30s</button> </div> ); }

🔧 Advanced Patterns

Custom Hook for Previous Value:

function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; } // Usage function Counter() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return ( <div> <p>Current: {count}</p> <p>Previous: {prevCount}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }

Imperative Handle Pattern:

import { forwardRef, useImperativeHandle, useRef } from "react"; const FancyInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); }, blur: () => { inputRef.current.blur(); }, select: () => { inputRef.current.select(); }, })); return <input ref={inputRef} {...props} />; }); // Usage function Form() { const inputRef = useRef(); const handleClick = () => { inputRef.current.focus(); }; return ( <div> <FancyInput ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </div> ); }

Storing Mutable Values:

function Timer() { const [count, setCount] = useState(0); const intervalRef = useRef(null); const startTimer = () => { intervalRef.current = setInterval(() => { setCount((c) => c + 1); }, 1000); }; const stopTimer = () => { if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } }; useEffect(() => { return () => { if (intervalRef.current) { clearInterval(intervalRef.current); } }; }, []); return ( <div> <p>Count: {count}</p> <button onClick={startTimer}>Start</button> <button onClick={stopTimer}>Stop</button> </div> ); }

⚠️ Important Notes

1. Refs Don't Trigger Re-renders:

// This won't cause a re-render myRef.current = newValue; // This will cause a re-render setState(newValue);

2. Initial Value:

const ref = useRef(null); // null is common for DOM refs const ref = useRef(0); // 0 for number values const ref = useRef({}); // {} for object values

3. Cleanup:

useEffect(() => { const timer = setInterval(() => { // Do something }, 1000); return () => { clearInterval(timer); // Clean up }; }, []);

🎯 Best Practices

  1. Use refs sparingly - prefer state when possible
  2. Always clean up timers and subscriptions
  3. Check if ref.current exists before using
  4. Use forwardRef for component refs
  5. Don't use refs for values that should trigger re-renders